package com.exp.bookhouse.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.exp.bookhouse.pojo.Book;
import com.exp.bookhouse.pojo.IPRecord;
import com.exp.bookhouse.service.BookService;
import com.exp.bookhouse.service.IPRecordService;
import com.exp.bookhouse.service.WebSettingService;
import com.exp.bookhouse.util.ApiJSONResult;
import com.exp.bookhouse.util.ConstUtils;
import com.exp.bookhouse.util.HttpClientUtil;
import com.exp.bookhouse.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Api(value = "图书管理接口",tags = "图书操作")
@RestController
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookService bookService;

    @Autowired
    private WebSettingService webSettingService;

    @Autowired
    private IPRecordService ipRecordService;

    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("/all")
    public List<Book> getAllBook(){
        return bookService.queryAllBook();
    }

    @GetMapping("/query")
    public List<Book> getBookByName(String name){
        return bookService.getBookByName(name);
    }

    @GetMapping("/id")
    public Book getBookId(Long id){
        return bookService.queryBookById(id);
    }

    @ApiOperation(value = "根据类别id获取图书信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "pageNum", value = "页数", required = true, dataType = "Int"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "显示记录数", required = true, dataType = "Int"),
            @ApiImplicitParam(paramType = "query", name = "categoryId", value = "图书类别id", required = true, dataType = "Int")
    })
    @GetMapping("/category")
    public ApiJSONResult queryPageBookByCategoryId(Integer pageNum, Integer pageSize, Integer categoryId, HttpServletRequest request){
        IPage<Book> books = bookService.queryBookByCategoryId(pageNum,pageSize,categoryId);

        //获取ip
        String ip = HttpClientUtil.getIp(request);
        //查询是否存在该ip
        IPRecord ipRecord = ipRecordService.queryIpByIp(ip);
        if(ipRecord != null){   //存在，判断1个小时之内是否重复登录
            long now = System.currentTimeMillis();
            long last = ipRecord.getUpdateTime().getTime();
            // 1小时 = 60 * 60 *1000 毫秒
            long hour = 60 * 60 * 1000;
            if(now - last > hour){  //超过一个小时，访问量加1,并更新时间
                webSettingService.updateViews();
                ipRecord.setUpdateTime(new Date());
                ipRecordService.updateIPTime(ipRecord);
            }
        }else{  //不存在，访问量加1，保存当前ip
            webSettingService.updateViews();
            IPRecord record = new IPRecord();
            record.setIp(ip);
            record.setUpdateTime(new Date());
            ipRecordService.saveIPRecord(record);
        }
        return ApiJSONResult.ok(books);
    }

    @ApiOperation(value = "根据搜索条件获取图书信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "pageNum", value = "页数", required = true, dataType = "Int"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "显示记录数", required = true, dataType = "Int"),
            @ApiImplicitParam(paramType = "query", name = "name", value = "图书名字", required = true, dataType = "String")
    })
    @GetMapping("/search")
    public ApiJSONResult getAllBookByName(Integer pageNum, Integer pageSize, String name){
        IPage<Book> bookList = bookService.queryBookByName(pageNum, pageSize, name);
        return ApiJSONResult.ok(bookList);
    }

    /**
     * 根据id查询书籍信息
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id查询书籍信息")
    @ApiImplicitParam(paramType = "query", name="id", value = "书籍id", required = true, dataType = "Long")
    @GetMapping("/{id}")
    public ApiJSONResult getBookById(@PathVariable("id") Long id){
        Book book = bookService.queryBookById(id);
        //将书籍的库存信息保存在redis中
        redisUtil.hset(ConstUtils.BOOK_STOCK,ConstUtils.BOOK_KEY + book.getId(),book.getStock());
        return ApiJSONResult.ok(book);
    }

    @ApiOperation(value = "根据id查询书籍库存信息")
    @ApiImplicitParam(paramType = "query", name="id", value = "书籍id", required = true, dataType = "Long")
    @GetMapping("/stock/{id}")
    public ApiJSONResult getStockById(@PathVariable("id") Long id){
        Integer stock = (Integer) redisUtil.hget(ConstUtils.BOOK_STOCK, ConstUtils.BOOK_KEY + id);
        return ApiJSONResult.ok(stock);
    }
}
